using System;
using System.Text.RegularExpressions;
using RPGOnline.Controls.Chat;
using RPGOnline.Remoting;
using RPGOnline.Remoting.Events;

namespace RPGOnline.Filters
{
    public class ConfigurationHandler : IMessageHandler
    {
        private readonly UserManager m_userManager;
        private Regex m_pgFormat = new Regex(@"^/pg\ (?<pgName>[^ ]+)");
        private Regex m_noPgFormat = new Regex(@"^/nopg");

        public event EventHandler<UserInfoChangedEventArgs> OnCharacterNameChanged;

        public ConfigurationHandler(UserManager userManager)
        {
            m_userManager = userManager;
        }

        public bool IsValid(string message)
        {
            return m_pgFormat.IsMatch(message) || m_noPgFormat.IsMatch(message);
        }

        public bool Handle(string message)
        {
            return HandlePg(message) || HandleNoPg(message);
        }

        public bool HandlePg(string message)
        {
            if (!m_pgFormat.IsMatch(message))
                return false;


            Match match = m_pgFormat.Match(message);

            Group pgName = match.Groups["pgName"];
            if (!pgName.Success)
                return false;

            m_userManager.CurrentUser.CharacterName = pgName.Value;
            if (OnCharacterNameChanged != null)
                OnCharacterNameChanged(this, new UserInfoChangedEventArgs(m_userManager.CurrentUser));

            return true;
        }

        public bool HandleNoPg(string message)
        {
            if (!m_noPgFormat.IsMatch(message))
                return false;

            m_userManager.CurrentUser.CharacterName = null;
            if (OnCharacterNameChanged != null)
                OnCharacterNameChanged(this, new UserInfoChangedEventArgs(m_userManager.CurrentUser));

            return true;
        }
    }
}